package cn.iocoder.yudao.framework.excel.core.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Locale;

public class DateConvert implements Converter<LocalDate> {

    // 支持的日期格式（按优先级尝试解析）
    private static final DateTimeFormatter[] SUPPORTED_FORMATTERS = {
            DateTimeFormatter.ofPattern("yyyy-MM-dd"),
            DateTimeFormatter.ofPattern("yyyy/MM/dd"),
            DateTimeFormatter.ofPattern("yyyyMMdd")
    };

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String dateStr = "";
        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            // Excel 数字（日期格式） → 转成 "yyyy-MM-dd"
            BigDecimal numberValue = cellData.getNumberValue();
            Date javaDate = DateUtil.getJavaDate(numberValue.doubleValue());
            dateStr = new SimpleDateFormat("yyyy-MM-dd").format(javaDate);
        } else if (cellData.getType() == CellDataTypeEnum.STRING) {
            dateStr = cellData.getStringValue();
        }

        if (StringUtils.isBlank(dateStr)) {
            throw new IllegalArgumentException("日期内容为空，无法解析");
        }

        // 尝试用多种格式解析日期
        for (DateTimeFormatter formatter : SUPPORTED_FORMATTERS) {
            try {
                return LocalDate.parse(dateStr, formatter);
            } catch (DateTimeParseException ignored) {
                // 尝试下一种格式
            }
        }
        throw new IllegalArgumentException("日期格式不支持，请使用 yyyy-MM-dd、yyyy/MM/dd 或 yyyyMMdd 格式");
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDate localDate, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        // 默认使用 "yyyy-MM-dd" 格式写入 Excel
        return new WriteCellData<>(localDate.format(SUPPORTED_FORMATTERS[0]));
    }
}